//
//  ICMusicPlayOpration.m
//  DWTeacher
//
//  Created by icochu on 2022/02/22.
//  Copyright © 2022年 wlf. All rights reserved.
//

#import "ICMusicPlayOpration.h"
@implementation ICMusicPlayOpration {
    dispatch_semaphore_t _lock;
}

- (instancetype)init{
    self = [super init];
    _currentPlayModelArray = @[];
    _currentPlayIndex = 0;
    _lock = dispatch_semaphore_create(1);
    self.objectAFN = [[ObjectAFNetWorking alloc]init];
    return self;
}
-(void)getListDataWithID:(NSString *)idStr Complete:(ListModelBlock)finshBlock
{
    /**取消掉*/
    [_objectAFN cancelRequest];
    NSLog(@"idStr----%@", idStr);
    [self.objectAFN getUrlStr:[NSString stringWithFormat:@"%@/api/index/Directory?id=%@",server_addr,idStr] finish:^(id  _Nonnull dataString) {
        
        NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        NSArray *listArray = dic[@"data"][@"data"];
        NSMutableArray *mutArray = [NSMutableArray array];
        for (NSDictionary *dict in listArray) {
            NSString *videoUrl =  dict[@"audio_url"];
            if (videoUrl.length > 0) {
                [mutArray addObject:dict];
            }
        }
        listArray = [NSArray arrayWithArray:mutArray];
        finshBlock(listArray);
    } andError:^(NSError * _Nonnull error) {
        
    }];
}
- (void)playNewMusicQueueWithModelArray:(NSArray *)musicModelArray
                                             Complete:(FinshModelBlock)finshBlock{
    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
    _currentPlayIndex = 0;
    _isFirstData = YES;
    _isLastData = (_currentPlayModelArray.count == 1) ? YES : NO;
    _currentPlayModelArray = musicModelArray;
    dispatch_semaphore_signal(_lock);
    CurriculumModel *model = musicModelArray[0];
    _currentPlayIndex = 0;
    [self getDataWithID:model Complete:finshBlock];
//    for (int i = 0; i < _currentPlayModelArray.count; i++) {
//        model = _currentPlayModelArray[i];
//        if (model.audio_url.length > 0) {
//            _currentPlayIndex = i;
//
//        }
//    }
}
- (void)saveLikeData:(ICMusicPlayModel *)playAutoModel{
    NSArray *dataArray = [[NSUserDefaults  standardUserDefaults] arrayForKey:@"CollectData"];
    if (dataArray == nil) {
        NSMutableArray *tempMutArray = [NSMutableArray array];
        [tempMutArray addObject:@{
            @"id": playAutoModel.id,
            @"data":playAutoModel.toDictionary
        }];
        [[NSUserDefaults  standardUserDefaults] setValue:tempMutArray forKey:@"getcatedetail"];
    }else{
        NSMutableArray *tempMutArray = [NSMutableArray arrayWithArray:dataArray];
       NSDictionary *dictData = @{
            @"id": playAutoModel.id,
            @"data":playAutoModel.toDictionary
       };
        BOOL isHave = NO;
        for (int i = 0; i < dataArray.count; i++) {
            NSDictionary *tempdict = dataArray[i];
            if ([tempdict[@"id"] isEqualToString:playAutoModel.id]) {
                [tempMutArray removeObjectAtIndex:i];
                [tempMutArray insertObject:dictData atIndex:0];
                isHave = YES;
                break;
            }
        }
        if (!isHave) {
            [tempMutArray insertObject:dictData atIndex:0];
        }

        [[NSUserDefaults  standardUserDefaults] setValue:tempMutArray.copy forKey:@"getcatedetail"];
    }
}
- (void)saveHistoryData:(ICMusicPlayModel *)playAutoModel{
    NSArray *dataArray = [[NSUserDefaults  standardUserDefaults] arrayForKey:@"getcatedetail"];
    if (dataArray == nil) {
        NSMutableArray *tempMutArray = [NSMutableArray array];
        [tempMutArray addObject:@{
            @"id": playAutoModel.id,
            @"data":playAutoModel.toDictionary
        }];
        [[NSUserDefaults  standardUserDefaults] setValue:tempMutArray forKey:@"getcatedetail"];
    }else{
        NSMutableArray *tempMutArray = [NSMutableArray arrayWithArray:dataArray];
       NSDictionary *dictData = @{
            @"id": playAutoModel.id,
            @"data":playAutoModel.toDictionary
       };
        BOOL isHave = NO;
        for (int i = 0; i < dataArray.count; i++) {
            NSDictionary *tempdict = dataArray[i];
            if ([tempdict[@"id"] isEqualToString:playAutoModel.id]) {
                [tempMutArray removeObjectAtIndex:i];
                [tempMutArray insertObject:dictData atIndex:0];
                isHave = YES;
                break;
            }
        }
        if (!isHave) {
            [tempMutArray insertObject:dictData atIndex:0];
        }

        [[NSUserDefaults  standardUserDefaults] setValue:tempMutArray.copy forKey:@"getcatedetail"];
    }
}
-(void)getDataWithID:(CurriculumModel *)model
            Complete:(FinshModelBlock)finshBlock
{
    /**取消掉*/
    [_objectAFN cancelRequest];
    NSLog(@"idStr----%@", model.id);
    NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/home_id%@_getcatedetail.json",model.id]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath])
    {
        NSData* dataString=[NSData dataWithContentsOfFile:filePath];
        NSDictionary* lastdic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        ICMusicPlayModel *playAutoModel = [[ICMusicPlayModel alloc] initWithDictionary:lastdic[@"data"] error:nil];
        playAutoModel.rownum = _currentPlayIndex;
        [self saveHistoryData:playAutoModel];
        finshBlock(playAutoModel);
        [GC_OCTool saveFileAction:filePath];
    }else{
        [self.objectAFN getUrlStr:[NSString stringWithFormat:@"%@/api/home/getcatedetail?id=%@",server_addr,model.id] finish:^(id  _Nonnull dataString) {
            
            NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
            NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/home_id%@_getcatedetail.json",model.id]];
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:nil];
            }
            NSLog(@"dic~~~>>%@",dic);
            ICMusicPlayModel *playAutoModel = [[ICMusicPlayModel alloc] initWithDictionary:dic[@"data"] error:nil];
            playAutoModel.pid = model.id;
            playAutoModel.rownum = self->_currentPlayIndex;
            [dataString writeToFile:filePath atomically:YES];
            [self saveHistoryData:playAutoModel];
            finshBlock(playAutoModel);
        } andError:^(NSError * _Nonnull error) {
            finshBlock(nil);
        }];
    }
}
- (void)playNewMusicQueueWithModelArray:(NSArray *)musicModelArray
                                            PlayIndex:(NSInteger)index
                                             Complete:(FinshModelBlock)finshBlock{
    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
    _currentPlayIndex = index;
    _currentPlayModelArray = musicModelArray;
    _isFirstData = (_currentPlayIndex == 0) ? YES : NO;
    _isLastData = (_currentPlayIndex == _currentPlayModelArray.count - 1) ? YES : NO;
    dispatch_semaphore_signal(_lock);
    CurriculumModel *model = musicModelArray[index];
    _currentPlayIndex = index;
    [self getDataWithID:model Complete:finshBlock];
//    for (NSInteger i = index; i < musicModelArray.count; i++) {
//        model = musicModelArray[i];
//
//        if (model.audio_url.length > 0) {
//            _currentPlayIndex = i;
//            break;
//        }
//    }
}

- (void)getNextModelComplete:(FinshModelBlock)finshBlock{
    CurriculumModel *model;
    //已经是最后一首没有下一首
    [[PlayModel  sharedModel] playNextSong];
    
    if ([PlayModel  sharedModel].currentIndex >= self.currentPlayModelArray.count || _isLastData) {
        finshBlock(nil);
        
    }
    model = self.currentPlayModelArray[[PlayModel  sharedModel].currentIndex];
    [self getDataWithID:model Complete:^(ICMusicPlayModel * _Nonnull model) {
        self.currentPlayIndex = [PlayModel  sharedModel].currentIndex;
        self.isFirstData = NO;
        self.isLastData = (self.currentPlayIndex == self.currentPlayModelArray.count - 1) ? YES : NO;
        finshBlock(model);
    }];
  
}

- (void)getFormerModelComplete:(FinshModelBlock)finshBlock{
    
    //第一首没有上一首
    if (_isFirstData)  finshBlock(nil);
    [[PlayModel sharedModel] playLastSong];
    CurriculumModel *model = _currentPlayModelArray[[PlayModel sharedModel].currentIndex];
    [self getDataWithID:model Complete:^(ICMusicPlayModel * _Nullable model) {
        self.currentPlayIndex = [PlayModel sharedModel].currentIndex;
        self.isFirstData = (self.currentPlayIndex == 0 ) ? YES : NO;
        self.isLastData =  NO;
        finshBlock(model);
    }];
//    for (NSInteger i = _currentPlayIndex; i > 0; i--) {
//        model = _currentPlayModelArray[i - 1];
//        if (model.audio_url.length > 0) {
//            _currentPlayIndex = i - 1;
//            _isFirstData = (_currentPlayIndex == 0 ) ? YES : NO;
//            _isLastData =  NO;
//            return model;
//        }
//    }
}

- (void)getIndexModelWith:(NSInteger)index
                               Complete:(FinshModelBlock)finshBlock{
    if (index < _currentPlayModelArray.count) {
        CurriculumModel *model = _currentPlayModelArray[index];
        [self getDataWithID:model Complete:^(ICMusicPlayModel * _Nullable model) {
            self.currentPlayIndex = index;
            self.isFirstData = (self.currentPlayIndex == 0) ? YES : NO;
            self.isLastData = (self.currentPlayIndex == self.currentPlayModelArray.count - 1) ? YES : NO;
            finshBlock(model);
        }];
       
    }
    
}

- (void)removeAllSelectData {
    dispatch_semaphore_wait(_lock, DISPATCH_TIME_FOREVER);
    _currentPlayIndex = 0;
    _currentPlayModelArray = @[].mutableCopy;
    _isFirstData = YES ;
    _isLastData = YES;
    dispatch_semaphore_signal(_lock);
}
@end
